/*
 * MinuteTimer.cpp
 *
 *  Created on: 2020年1月11日
 *      Author: terry
 */

#include "MinuteTimer.h"
#include "DateTime.h"
#include <algorithm>
#include "CLog.h"


const int MinuteTimer::DEF_INTERVAL = 50 * 1000;


MinuteTimer::MinuteTimer():
	m_minuteHandler(),
	m_hourHandler()
{
}

MinuteTimer::~MinuteTimer()
{
	close();
}

void MinuteTimer::setMinuteHandler(MinuteHandler handler)
{
	m_minuteHandler = handler;
}

void MinuteTimer::setHourHandler(HourHandler handler)
{
	m_hourHandler = handler;
}

bool MinuteTimer::open()
{
	if (isOpen())
	{
		close();
	}

	bool got = start();

	setName("MinuteTimer");

	return got;
}

void MinuteTimer::close()
{
	if (isRunning())
	{
		stop();
	}
}

bool MinuteTimer::isOpen()
{
	return isRunning();
}

void MinuteTimer::resetTime()
{
	m_event.post();
}

int MinuteTimer::run()
{
	while (!m_canExit)
	{
		int interval = checkTime();
		m_event.timedwait(interval);
	}
	return 0;
}

void MinuteTimer::doStop()
{
	m_event.post();
}

int64_t MinuteTimer::getClock()
{
	return comn::DateTime::getTime();
}

int MinuteTimer::checkTime()
{
	int ms = DEF_INTERVAL;

	int64_t clock = getClock();
	comn::DateTime dt = comn::DateTime::now();
	if (dt.getSecond() <= 2)
	{
		int day = dt.getDay();
		int minute = dt.getMinute();

		fireMinute(clock / 1000, day, dt.getHour(), minute);

		if (minute == 0)
		{
			fireHour(clock / 1000, day, dt.getHour());
		}
	}
	else
	{
		ms = 60 * 1000 - (dt.getSecond() * 1000 + dt.getMillisecond());
		ms = std::min(DEF_INTERVAL, ms);
	}

	//CLog::debug("MinuteTimer::checkTime. second: %d. delay: %d\n", dt.getSecond(), ms);

	return ms;
}

void MinuteTimer::fireMinute(int64_t clock, int mday, int hour, int minute)
{
	if (m_minuteHandler)
	{
		m_minuteHandler(clock, mday, hour, minute);
	}
}

void MinuteTimer::fireHour(int64_t clock, int mday, int hour)
{
	if (m_hourHandler)
	{
		m_hourHandler(clock, mday, hour);
	}
}
